//
//  SCIntegralCartController.m
//  shangcheng
//
//  Created by 张艳江 on 2019/6/9.
//  Copyright © 2019 张艳江. All rights reserved.
//

#import "SCIntegralCartController.h"
#import "SCCartGoodsListCell.h"
#import "SCCartSectionView.h"
#import "SCIntegralOrderController.h"

@interface SCIntegralCartController ()<UITableViewDelegate,UITableViewDataSource,SCCartGoodsListCellDelegate>

@property (weak, nonatomic) IBOutlet UIView   *bottomView;
@property (weak, nonatomic) IBOutlet UIButton *allSelectBtn;
@property (weak, nonatomic) IBOutlet UIButton *settlementBtn;
@property (weak, nonatomic) IBOutlet UILabel  *allAmountLab;
@property (weak, nonatomic) IBOutlet UILabel  *detaileLab;
@property (weak, nonatomic) IBOutlet UIView   *coverBgView;

@property (strong, nonatomic) UITableView    *tableView;
@property (strong, nonatomic) NSMutableArray *dataArray;
@property (strong, nonatomic) NSMutableArray *selectArray;

@end

@implementation SCIntegralCartController

- (void)zj_viewDidAppearForIndex:(NSInteger)index{
    if (self.scrollWithIndex) {
        self.scrollWithIndex(index);
    }
    self.coverBgView.hidden = YES;
    self.allSelectBtn.selected = NO;
    [SVProgressHUD showWithStatus:@"加载中..."];
    [self requestData];
}
- (void)zj_viewDidDisappearForIndex:(NSInteger)index{
    [self.settlementBtn setTitle:@"去结算" forState:0];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = BGColor;
    //设置tableView
    [self setUpTableView];
    
    //基本h设置
    self.bottomView.hidden = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickEditButton:) name:@"ClickEditButton" object:nil];
}
- (void)clickEditButton:(NSNotification *)notf{
    
    NSDictionary *dict = notf.object;
    if ([dict[@"scrollIndex"] intValue] == 0) {
        if ([dict[@"editbool"] intValue] == 0) {
            [self.settlementBtn setTitle:@"去结算" forState:0];
            self.coverBgView.hidden = YES;
        }else{
            [self.settlementBtn setTitle:@"删除" forState:0];
            self.coverBgView.hidden = NO;
        }
    }
}
- (void)setUpTableView{
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH-kTopHeight-kTabBarHeight-50-38) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = BGColor;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 110;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 8)];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SCCartGoodsListCell" bundle:nil] forCellReuseIdentifier:@"SCCartGoodsListCellID"];
    [self.view addSubview:self.tableView];
}
#pragma mark - 表格
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    SCModel *model = self.dataArray[section];
    return model.list.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 48;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    static NSString *headerID = @"header";
    UITableViewHeaderFooterView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerID];
    if (header == nil) {
        header = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:headerID];
        SCCartSectionView *headerView = [SCCartSectionView addCartSectionView];
        headerView.frame = CGRectZero;
        [header addSubview:headerView];
    }
    for (UIView *View in header.subviews) {
        if ([View isKindOfClass:[SCCartSectionView class]]) {
            SCCartSectionView *headerView = (SCCartSectionView *)View;
            headerView.sectionModel = self.dataArray[section];
            headerView.headSelectBtn.tag = section;
            [headerView.headSelectBtn addTarget:self action:@selector(clickHeadSelectBtn:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    return header;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SCCartGoodsListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SCCartGoodsListCellID"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    SCModel *model = self.dataArray[indexPath.section];
    cell.model = model.list[indexPath.row];
    cell.model.section = indexPath.section;
    cell.delegate = self;
    return cell;
}
#pragma mark - 点击head的选中按钮
- (void)clickHeadSelectBtn:(UIButton *)sender{
    
    SCModel *model = self.dataArray[sender.tag];
    if (model.headClickState == 0) {
        model.headClickState = 1;
        for (SCModel *cellModel in model.list) {
            cellModel.cellSelectState = 1;
        }
    }else{
        model.headClickState = 0;
        for (SCModel *cellModel in model.list) {
            cellModel.cellSelectState = 0;
        }
    }
    [self calculationPrice];
}
#pragma mark - cell的代理
- (void)clickCartCellButton:(SCModel *)model tag:(NSInteger)tag{
    
    if (tag == 10) {
        int i = 0;
        SCModel *headModel = self.dataArray[model.section];
        for (SCModel *cellModel in headModel.list) {
            if (cellModel.cellSelectState == 1) {
                i++;
            }
        }
        if (i == headModel.list.count) {
            headModel.headClickState = 1;
        }else{
            headModel.headClickState = 0;
        }
        [self calculationPrice];
    }else{//加减
        int type = (int)tag - 11;
        NSDictionary *dict = @{@"token":Token,
                               @"cart_id":model.cart_id,
                               @"type":@(type)};
        NSString *url;
        if (self.isGiftApp == YES) {
            url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GiftCart&a=upCart"];
        }else{
            url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GoodsAppCart&a=upCart"];
        }
        [[NetworkRequestTool sharedNetworkTool] POST:url parameters:dict finished:^(id result, NSString *error) {
            //NSLog(@"----%@",result);
            [self calculationPrice];
        }];
    }
}
#pragma mark - 点击下部全选按钮
- (IBAction)clickAllSelectBtn:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    if (sender.selected == YES) {
        for (SCModel *sectionModel in self.dataArray) {
            sectionModel.headClickState = 1;
            for (SCModel *cellModel in sectionModel.list) {
                cellModel.cellSelectState = 1;
            }
        }
    }else{
        for (SCModel *sectionModel in self.dataArray) {
            sectionModel.headClickState = 0;
            for (SCModel *cellModel in sectionModel.list) {
                cellModel.cellSelectState = 0;
            }
        }
    }
    [self calculationPrice];
}
#pragma mark - 计算价格
- (void)calculationPrice{

    [self.tableView reloadData];
    
    self.selectArray = [NSMutableArray array];
    int allGoodsNum = 0;//商品总数
    for (SCModel *headModel in self.dataArray) {
        for (SCModel *cellModel in headModel.list) {
            if (cellModel.cellSelectState == 1) {
                [self.selectArray addObject:cellModel];
            }
            allGoodsNum++;
        }
    }
    if (self.selectArray.count == 0) {
        self.allAmountLab.text = @"0.00";
        self.allSelectBtn.selected = NO;
        return;
    }else{
        //设置全选按钮状态
        if (self.selectArray.count == allGoodsNum) {
            self.allSelectBtn.selected = YES;
        }else{
            self.allSelectBtn.selected = NO;
        }
        NSString *allMoney = @"0";
        for (SCModel *goodsModel in self.selectArray) {
            
            NSString *money;
            if (self.isGiftApp == YES) {
                money = [CGPriceTool decimalNumberCalucate:goodsModel.gift_fen originValue2:[NSString stringWithFormat:@"%d",goodsModel.gift_num] calucateWay:Multiplying];
            }else{
                money = [CGPriceTool decimalNumberCalucate:goodsModel.goods_price originValue2:[NSString stringWithFormat:@"%d",goodsModel.count] calucateWay:Multiplying];
            }
            allMoney = [CGPriceTool decimalNumberCalucate:allMoney originValue2:money calucateWay:Adding];
        }
        if (self.isGiftApp == YES) {
            self.allAmountLab.text = [NSString stringWithFormat:@"%@福豆",[MyTool removeFloatAllZeroByString:allMoney]];
        }else{
            self.allAmountLab.text = [NSString stringWithFormat:@"¥%@",[MyTool removeFloatAllZeroByString:allMoney]];
        }
    }
}
#pragma mark - 请求数据
- (void)requestData{
    
    //NSLog(@"请求购物车了");
    NSDictionary *dict = @{@"token":Token,
                           @"pagenow":@(1),
                           @"size":@(100)};
    NSString *url;
    if (self.isGiftApp == YES) {
        url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GiftCart&a=selectall"];
    }else{
        url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GoodsAppCart&a=selectall"];
    }
    [[NetworkRequestTool sharedNetworkTool] POST:url parameters:dict finished:^(id result, NSString *error) {
        NSLog(@"===%@",result);
        if ([self.settlementBtn.titleLabel.text isEqualToString:@"去结算"]) {
            [SVProgressHUD dismiss];
        }else{
            [SVProgressHUD showSuccessWithStatus:@"删除成功"];
        }

        NSArray *tempArray;
        if (self.isGiftApp == YES) {
            tempArray = [SCModel mj_objectArrayWithKeyValuesArray:result[@"data"][@"data"]];
        }else{
            tempArray = [SCModel mj_objectArrayWithKeyValuesArray:result[@"data"][@"list"]];
        }
        for (SCModel *model in tempArray) {
            model.list = [SCModel mj_objectArrayWithKeyValuesArray:model.list];
        }
        self.dataArray = [NSMutableArray array];
        [self.dataArray addObjectsFromArray:tempArray];
        if (self.dataArray.count > 0) {
            self.bottomView.hidden = NO;
        }else{
            self.bottomView.hidden = YES;
        }
        [self.tableView reloadData];
    }];
}
//点击结算
- (IBAction)clickSettlementBtn:(UIButton *)sender {
    
    if (self.selectArray.count == 0) {
        [SVProgressHUD showImage:nil status:@"请先选中商品!"];
        return;
    }
    if ([sender.titleLabel.text isEqualToString:@"去结算"]) {
        SCIntegralOrderController *vc = [[SCIntegralOrderController alloc]init];
        vc.isGiftApp = self.isGiftApp;
        vc.goodsArray = [self.selectArray copy];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        
        [MyTool alertTitle:@"您确定要删除选择的商品吗?" mesasge:nil preferredStyle:UIAlertControllerStyleAlert confirmHandler:^(UIAlertAction * _Nonnull action) {
            
            NSMutableArray *mutArray = [NSMutableArray array];
            for (SCModel *model in self.selectArray) {
                [mutArray addObject:model.cart_id];
            }
            NSString *ids = [[mutArray copy] componentsJoinedByString:@","];
            NSDictionary *dict = @{@"token":Token,
                                   @"cart_id":ids};
            //NSLog(@"提交的参数：%@",dict);
            NSString *url;
            if (self.isGiftApp == YES) {
                url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GiftCart&a=delMuchCart"];
            }else{
                url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GoodsAppCart&a=delCart"];
            }
            [[NetworkRequestTool sharedNetworkTool] POST:url parameters:dict finished:^(id result, NSString *error) {
                self.allAmountLab.text = @"0.00";
                self.allSelectBtn.selected = NO;
                [SVProgressHUD showWithStatus:@"删除中..."];
                [self requestData];
            }];
        } cancleHandler:nil viewController:self];
    }
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
